import axios from 'axios'
import { apiUrl } from './constant'

const apiGetUser = `${apiUrl}/user`
const apiGetMenu = `${apiUrl}/user/getMenu`
const apiGetHelp = `${apiUrl}/role/getModuleList`

const request = (url) => {
    return new Promise((resolve, reject) => {
        axios.get(url)
            .then(res => {
                resolve(res)
            })
            .catch(res => {
                reject(res)
            })
    })
}

export function getUser(user) {
  return request(`${apiGetUser}/?name=${user}`)
}

export function getMenu(userName) {
  return request(`${apiGetMenu}/?data=${encodeURI(JSON.stringify({userName}))}`)
}

export function getHelp(moduleId) {
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url: apiGetHelp,
            data: 'data=' + encodeURI(JSON.stringify({moduleId: moduleId}))
        }).then(res => {
                resolve(res)
        }).catch(res => {
                reject(res)
        })
    })
}

export function fetchData (url, method, data)  {
    let _url = `${apiUrl}${url}`
    let config = {
        method: method,
        url: _url,
        headers:{
            'Content-type': 'application/x-www-form-urlencoded'
        }
    }
    if(method === 'get') {
        if (data) {
            _url += `?data=${data}`
        }
        config.url = _url;
    } else if (method === 'post') {
        config.data = 'data=' + data;
    }
    return axios(config);
}